<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;" class="clearfix">
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        style="float:right"
        @click="handleAdd"
      >新增</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column label="序号" align="center" width="200" fixed>
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="160px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDel(row,$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogType"
      :visible.sync="dialogVisible"
      width="900px"
      @close="$refs['form'].clearValidate()"
      @opened="$refs['form'].clearValidate()"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入名称" clearable @change="validRepeatName" />
          <i v-if="isRegister == 0 && isRegister !== null" class="el-icon-check"> 通过</i>
          <i v-if="isRegister == 1 && isRegister !== null" class="el-icon-close"> 职位已存在</i>
        </el-form-item>
        <el-form-item label="职位描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" autosize placeholder="请输入备注" clearable />
        </el-form-item>
        <el-form-item label="权限设置">
          <tree-transfer
            :title="transferTitle"
            :from_data="fromData"
            :to_data="toData"
            :default-props="{label:'name'}"
            pid="parentId"
            mode="transfer"
            height="500px"
            :filter="false"
            open-all
            @addBtn="add"
            @removeBtn="remove"
          />
        </el-form-item>
        <!-- <el-form-item label="是否启用">
          <el-switch v-model="form.status" />
        </el-form-item>-->
        <el-form-item>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import * as Position from '@/api/system'
import treeTransfer from 'el-tree-transfer'

export default {
  name: 'PositionList',
  directives: { waves },
  components: { Pagination, treeTransfer },
  data() {
    return {
      tableKey: 0,
      list: null,
      validateRepeatArray: null,
      total: 0,
      listLoading: true,
      orgId: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        orgId: 0
      },
      rules: {
        roleName: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入职位名称'
          }
        ],
        remark: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入职位描述'
          }
        ]
      },
      form: {
        id: '',
        roleName: '',
        remark: '',
        status: false
      },
      dialogVisible: false,
      dialogType: '',

      transferTitle: ['全部权限', '已选权限'],
      fromData: [], // 左侧数据
      toData: [], // 右侧数据
      permissionList: [], // 新增职位(已选权限)
      chooseIdList: [], // 已选择的权限id
      returnBackList: [], // 拷贝返回已有权限,
      isRegister: null,
      isEmpty: false
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      Position.organizePositionList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleDel(row, index) {
      this.$confirm('是否确认删除该部门？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        Position.organizePositionDelete({
          id: row['id']
        }).then((response) => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    },
    handleUpdate(row) {
      this.dialogType = '职位编辑'
      this.isRegister = 0
      this.dialogVisible = true
      this.form.id = row['id']
      this.form.roleName = row['roleName']
      this.form.remark = row['remark']
      this.form.status = row['status'] === 1
      this.refreshAllRoleList()
      this.alreadyRoleList(row['id'])
    },
    // 权限菜单
    refreshAllRoleList() {
      Position.organizePositionRoleList({ systemType: '2' }).then((response) => {
        console.log(response)
        this.fromData = response.data
      })
    },
    // 已选权限
    alreadyRoleList(id) {
      Position.organizePositionCheckNewList({ id: id }).then((res) => {
        // // 已有权限深拷贝
        this.returnBackList = JSON.parse(JSON.stringify(res.data))
        this.toData = res.data
      })
    },
    handleAdd() {
      this.dialogType = '添加职位'
      this.isRegister = null
      this.dialogVisible = true
      this.form.id = ''
      this.form.roleName = ''
      this.form.remark = ''
      this.form.status = false
      this.fromData = []
      this.toData = []
      this.refreshAllRoleList()
    },
    async validRepeatName() {
      if (this.form.roleName === '') return
      Position.validateRoleName({ orgId: this.orgId, roleName: this.form.roleName }).then(res => {
        console.log(res.data.exist)
        this.isRegister = res.data.exist === 1 ? 1 : 0
      })
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.status = this.form.status ? '1' : '0'
          if (this.dialogType === '添加职位') {
            if (this.isRegister !== 0) return
            if (this.permissionList.length === 0) {
              this.$message({ message: '请选择职位权限', type: 'error' })
              return
            } else {
              Position.organizePositionAdd({
                orgId: this.orgId,
                roleName: this.form.roleName,
                remark: this.form.remark,
                permissionList: this.permissionList
              }).then((response) => {
                this.$message({ message: '提交成功', type: 'success' })
                this.dialogVisible = false
                this.getList()
              })
            }
          } else if (this.dialogType === '职位编辑') {
            if (this.isEmpty) {
              this.$message({ message: '请至少选择一个权限', type: 'error' })
              return
            }
            if (this.isRegister !== 0 || this.isRegister == null) return
            Position.organizePositionUpdate({
              id: this.form.id,
              roleName: this.form.roleName,
              remark: this.form.remark,
              orgId: this.orgId,
              permissionList: [{}]
            }).then((response) => {
              this.$message({ message: '提交成功', type: 'success' })
              this.dialogVisible = false
              this.isEmpty = false
              this.getList()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 监听穿梭框组件添加
    async add(fromData, toData, obj) {
      this.isEmpty = toData.length === 0
      this.isEmpty = toData.length === 0
      obj['keys'] = obj['keys'].concat(obj['harfKeys'])
      if (this.dialogType === '添加职位') {
        this.permissionList = []
        const handleParams = [] // 处理参数的数组
        this.loopAddIdList(toData, this.permissionList)
        console.log(this.permissionList)
        this.permissionList.forEach((v) => {
          const newObj = {}
          newObj['permissionId'] = v
          handleParams.push(newObj)
        })
        this.permissionList = handleParams
        console.log(this.permissionList)
      } else if (this.dialogType === '职位编辑') {
        const alreadyHasIdList = []
        const uploadIdList = []
        this.loopChooseId(this.returnBackList, alreadyHasIdList)
        alreadyHasIdList.forEach((item, index) => {
          obj['keys'].forEach((item2, index2) => {
            if (item === item2) {
              obj['keys'].splice(index2, 1)
            }
          })
        })
        this.handleParams(obj['keys'], uploadIdList)
        if (uploadIdList.length === 0) return
        await Position.organizePositionAddList(uploadIdList)
        await Position.organizePositionCheckNewList({ id: this.form.id }).then((res) => {
          this.returnBackList = JSON.parse(JSON.stringify(res.data))
        })
      }
    },
    // 监听穿梭框组件移除
    remove(fromData, toData, obj) {
      this.isEmpty = toData.length === 0
      if (this.dialogType === '添加职位') {
        this.permissionList = []
        this.loopRemoveIdList(toData, this.permissionList)
      } else if (this.dialogType === '职位编辑') {
        if (obj['harfKeys'].length > 0) {
          obj['keys'].forEach((item, index) => {
            obj['harfKeys'].forEach((item2, index2) => {
              if (item === item2) {
                obj['keys'].splice(index, 1)
              }
            })
          })
        }
        const delList = []
        const alreadyChooseIdList = []
        this.recursionMainId(this.returnBackList, alreadyChooseIdList)
        // console.log(alreadyChooseIdList,'已有权限id和mainId集合');
        for (const chooseId of obj['keys']) {
          for (const alreadyId of alreadyChooseIdList) {
            if (chooseId === alreadyId['id']) {
              delList.push(alreadyId['mainId'])
            }
          }
        }
        Position.organizePositionDeleteList(delList)
      }
    },
    // 遍历权限的id列表
    loopChooseId(arrayData, emptyArray) {
      arrayData.forEach(item => {
        emptyArray.push(item.id)
        if (item.children.length > 0) {
          this.loopChooseId(item.children, emptyArray)
        }
      })
      return emptyArray
    },
    // 处理需要传的参数
    handleParams(data, arr) {
      if (data.length === 0) return
      data.forEach((item, index) => {
        const paramsObj = {}
        paramsObj['orgId'] = String(this.orgId)
        paramsObj['roleId'] = String(this.form.id)
        paramsObj['permissionId'] = String(item)
        arr.push(paramsObj)
      })
      return arr
    },
    // 递归已有权限的id/mainId
    recursionMainId(returnBackList, emptyArray) {
      returnBackList.forEach(item => {
        const obj = {}
        obj['id'] = item.id
        obj['mainId'] = item.mainId
        obj['name'] = item.name
        emptyArray.push(obj)
        if (item.children.length > 0) {
          this.recursionMainId(item.children, emptyArray)
        }
      })
      return emptyArray
    },
    // 递归添加权限id集合
    loopAddIdList(rightData, emptyArray) {
      rightData.forEach(item => {
        emptyArray.push(item.id)
        if (item.children.length > 0) {
          this.loopAddIdList(item.children, emptyArray)
        }
      })
      return emptyArray
    },
    // 递归移除的权限id集合
    loopRemoveIdList(rightData, emptyArray) {
      rightData.forEach(item => {
        const obj = {}
        obj['permissionId'] = item.id
        emptyArray.push(obj)
        if (item.children.length > 0) {
          this.loopRemoveIdList(item.children, emptyArray)
        }
      })
      return emptyArray
    }
  }
}
</script>

<style lang="scss" scoped>
/deep/ .el-dialog{
  margin-top: 11vh;
}
/deep/ .el-dialog__body{
  padding: 20px;
}

/deep/ .el-input{
  width: 78%;
}

/deep/ .el-textarea{
  width: 78%;
}
.el-icon-check{
  margin-left: 10px;
  color: green;
}
.el-icon-close{
  margin-left: 10px;
  color: red;
}
</style>
